<template>
	<view>
		<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
		<u--form labelPosition="left" :model="model1" :rules="rules" ref="uForm">
			<u-form-item v-if="model1.userInfo.avatar==null" label="头像" prop="userInfo.avatar" borderBottom ref="item1">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="1"></u-upload>
			</u-form-item>
			<u-form-item v-else label="头像" prop="userInfo.avatar" borderBottom ref="item1">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					:maxCount="1">
					<!-- <image :src="model1.userInfo.avatar" mode="widthFix" style="width: 150rpx;height: 150rpx;"></image> -->
					<u-avatar :src="model1.userInfo.avatar" :size="100"></u-avatar>
				</u-upload>
			</u-form-item>
			<u-form-item label="昵称" prop="userInfo.nickName" borderBottom ref="item1">
				<u--input v-model="model1.userInfo.nickName" border="none"></u--input>
			</u-form-item>
			<u-form-item label="个性签名" prop="userInfo.signature" borderBottom ref="item1">
				<u--input v-model="model1.userInfo.signature" border="none"></u--input>
			</u-form-item>
			<u-form-item label="性别" prop="userInfo.sex" borderBottom @click="showSex = true; hideKeyboard()"
				ref="item1">
				<u--input v-model="model1.userInfo.sex" disabled disabledColor="#ffffff" placeholder="请选择性别"
					border="none"></u--input>
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
		</u--form>
		<u-action-sheet :show="showSex" :actions="actions" title="请选择性别" @close="showSex = false" @select="sexSelect">
		</u-action-sheet>
		<u-button type="primary" @click="submit">保存</u-button>
		<view class="footer">
			<text class="f-text" @click="goLogout">退出账号</text>
		</view>
	</view>
</template>

<script>
	import store from '../../store';
	import {
		getUserInfo,
		logout,
		savaUserInfo
	} from '../../api/user';
	import {
		removeToken
	} from '../../utils/auth';
	export default {
		data() {
			return {
				fileList1: [],
				showSex: false,
				model1: {
					userInfo: {
						// avatar: null,
						// nickName: '',
						// sex: '',
						// signature: '',
					},
				},
				actions: [{
						name: '男',
						value: 0
					},
					{
						name: '女',
						value: 1
					},
					{
						name: '未知',
						value: 2
					},
				],
				rules: {
					'userInfo.nickName': {
						type: 'string',
						required: true,
						message: '请填写昵称',
						trigger: ['blur', 'change']
					},
					'userInfo.sex': {
						type: 'string',
						max: 1,
						required: true,
						message: '请选择男或女',
						trigger: ['blur', 'change']
					},
				},
				radio: '',
				switchVal: false
			};
		},
		onLoad() {
			this.getDetail()
		},
		methods: {
			goLogout() {
				logout().then(() => {
					// 返回到上一页
					uni.navigateBack({
						delta: 1 // 1表示返回1页，可以设置为任意整数
					});
					// 清除登录相关的缓存
					removeToken()
					uni.removeStorageSync("user-info")
				})
			},
			getDetail() {
				getUserInfo().then((res) => {
					// console.log(res);
					this.model1.userInfo = res
					this.model1.userInfo.sex = this.model1.userInfo.sex == 0 ? '男' : (this.model1.userInfo.sex ==
						1 ? '女' : '未知')

				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: store.state.baseURL + '/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'img',
						formData: {
							user: 'test'
						},
						success: (res) => {
							this.model1.userInfo.avatar = JSON.parse(res.data).data
							console.log(JSON.parse(res.data).data);
							setTimeout(() => {
								resolve()
							}, 1000)
						}
					});
				})
			},
			submit() {
				this.$refs.uForm.validate().then(res => {
					this.model1.userInfo.sex = this.model1.userInfo.sex == '男' ? 0 : (this.model1.userInfo.sex ==
						'女' ? 1 : 2)
					savaUserInfo(this.model1.userInfo).then(() => {
						//修改缓存中的用户信息
						uni.setStorageSync('user-info', this.model1.userInfo);
						uni.$u.toast('资料修改成功')
						// 返回到上一页
						uni.navigateBack({
							delta: 1 // 1表示返回1页，可以设置为任意整数
						});
					}).catch(err => {
						this.model1.userInfo.sex = this.model1.userInfo.sex == 0 ? '男' : (this.model1
							.userInfo.sex ==
							1 ? '女' : '未知')
					})
				}).catch(errors => {
					// uni.$u.toast('校验失败')
					console.log("校验失败");
				})
			},
			sexSelect(e) {
				this.model1.userInfo.sex = e.name
				this.$refs.uForm.validateField('userInfo.sex')
			},
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.uForm.setRules(this.rules)
		},
	};
</script>


<style lang="scss">
	.footer {
		position: fixed;
		left: 320rpx;
		bottom: 80rpx;


		.f-text {
			color: royalblue;
		}
	}
</style>